#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
import gobject
import datetime 
from DateWidget import DateWidget,ANOTHER_DAY_FMT
from EventWidget import EventWidget
import gnomeagenda.appointment
from gettext import gettext as _

#from MouseOverLabel import MouseOverLabel

color_light = gtk.gdk.color_parse('#EEEEEE')

class AgendaListView (gtk.VBox):
	"""The list-view of the agenda"""
	def __init__(self):
		""" """
		gtk.VBox.__init__(self)
		self.show_all()

		pass
	def getEventWidget(self,row):
		wrapper = EventWidget(row)
		wrapper.show()
		return wrapper
	def getDateWidget(self,date):
		"""
		Get the DateWidget
		"""
		wrapper = DateWidget(date)
		wrapper.show()
		return wrapper	
		
	def updateView(self,resultRows):
		now = datetime.datetime.utcnow()
		"""updates the List View"""
		for c in self.get_children():
			c.destroy()
			pass
		k = 0
		print datetime.datetime.utcnow() - now
		date = None
		
		nextUpdateTime = datetime.timedelta(days=1) + datetime.datetime.utcnow().replace(hour = 0, minute = 0, second = 0, microsecond = 0)
		#print nextUpdateTime
		for cal_event in resultRows:

			rowDate = cal_event.getStartDate()		
			event_widget = self.getEventWidget(cal_event)
			
			if date != rowDate:
				k = k+1
				date_widget = self.getDateWidget(rowDate )
				self.pack_start(date_widget,False)
				if(k % 2 == 0):
					date_widget.modify_bg(date_widget.state,date_widget.style.white)
				else:
					date_widget.modify_bg(date_widget.state,color_light)
				#pass
				
		
			if(cal_event.is_all_day()):
				#all day events should initiate a redraw one day after they start, not when they end
				date_widget.addEvent(event_widget)
				event_end_time = cal_event.start_time + datetime.timedelta(days=1)
				nextUpdateTime = new_next_update_time(nextUpdateTime, event_end_time,now)
			else:
				if(not cal_event.is_past()):
					
					date_widget.addEvent(event_widget)
					nextUpdateTime = new_next_update_time(nextUpdateTime, cal_event.end_time,now)
				else:
					date_widget.addEvent(event_widget)
				if(not cal_event.is_now()):
					nextUpdateTime = new_next_update_time(nextUpdateTime, cal_event.start_time,now)
			date = rowDate

		null = gtk.EventBox()
		null.show_all()
		self.pack_start(null)
		null.modify_bg(null.state,null.style.white)
		
		#redraw as soon as the next event is over
		#print nextUpdateTime
		#get the event that ends as next, and redraw right after this
		
		print datetime.datetime.utcnow() - now

		return gnomeagenda.appointment.utc2local(nextUpdateTime)
def new_next_update_time(next_update,new,now):
	
	if (new > next_update):
		return next_update
	if (new < now):
		return next_update
	
	return min(new,next_update)
